package com.atguigu.daijia.common.login;

import cn.hutool.core.util.StrUtil;
import com.atguigu.daijia.common.code.RedisCache;
import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.common.util.AuthContextHolder;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @description:自定义登录校验实现
 * @name: GuiguLoginAspect
 * @author: wgp
 * @date: 2024/8/12 13:51
 */

@Component
@Aspect
public class GuiguLoginAspect {

    @Resource
    private RedisCache redisCache;

    @Around("execution(* com.atguigu.daijia.*.controller.*.*(..)) && @annotation(guiguLogin)")
    public Object login(ProceedingJoinPoint proceedingJoinPoint, GuiguLogin guiguLogin) throws Throwable {
        //1 获取request对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //2 获取请求头中的TOken
        String token = request.getHeader("token");
        //3判断token是否为空，如果为空，则返回提示登录
        if (StrUtil.isBlank(token)) {
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        //4 token不为空，查询redis
        String customerId = redisCache.getCacheObject(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
        //5 查询redis对应的用户id 然后放在ThreadLocal中
        if (StrUtil.isNotBlank(customerId)) {
            AuthContextHolder.setUserId(Long.parseLong(customerId));
        }
        //6 执行业务方法
        return proceedingJoinPoint.proceed();
    }

}
